package net.p2pcdn.task;

import net.p2pcdn.common.Date2StringConverter;
import net.p2pcdn.core.order.domain.ExpiringContract;
import net.p2pcdn.core.order.repository.ContractRepository;
import net.p2pcdn.core.order.repository.ExpiringContractRepository;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 每分钟 扫描一次
 *
 * @author zx
 */
@Component
public class ExpireContractExecutor {
    @Resource
    private ExpiringContractRepository expiringContractRepository;
    @Resource
    private ContractRepository contractRepository;

    @Scheduled(cron = "0 */1 * * * ?")
    public void execute() {
        Map<String, Object> params = new HashMap<>(7);
        params.put("from", DateUtils.addMinutes(new Date(), -5));
        params.put("to", DateUtils.addMinutes(new Date(), 5));
        params.put("now", Date2StringConverter.yyyyMMddHHmm(new Date()));
        List<ExpiringContract> contractList = expiringContractRepository.query(params);
        if (!contractList.isEmpty()) {
            contractRepository.expireContracts(contractList.stream().map(ExpiringContract::getContractId).collect(Collectors.toList()));
            expiringContractRepository.done(contractList);
        }

    }
}
